package componentInit

import (
	"fmt"
	"db2s/global"
	mq "db2s/topic-mq"
	"sync/atomic"
	"time"
)

func (a *AutoCloseMqComponent) TopicEndDelete(topic Topic) {
	atomic.AddInt64(a.TopicStatistics[topic], -1)
}
func (a *AutoCloseMqComponent) TopicEndDeleteNumber(topic Topic, n int64) {
	atomic.AddInt64(a.TopicStatistics[topic], n)
}
func (a *AutoCloseMqComponent) TopicEndAdd(topic Topic) {
	atomic.AddInt64(a.TopicStatistics[topic], 1)
}
func (a *AutoCloseMqComponent) TopicEndMonit(topic Topic) int64 {
	return atomic.LoadInt64(a.TopicStatistics[topic])
}
func (a *AutoCloseMqComponent) ObjectEndMark() {
	a.EndMark = true
}
func (a *AutoCloseMqComponent) Close(print bool) {
	go func(c *AutoCloseMqComponent) {
		ticker := time.NewTicker(1 * time.Second)
		for {
			select {
			case <-ticker.C:
				for _, l := range checkType[a.CheckMode] {
					if c.UnsubscribeTopicInclude(l.TopicName) {
						continue
					}
					val := atomic.LoadInt64(c.TopicStatistics[l.TopicName])
					//查询是否满足取消订阅
					ok := c.checkUnsubscribeTopic(val, l.TopicName)
					//不满足退出
					if ok {
						break
					}
				}
				if print {
					fmt.Printf("============================================ \n")
					for _, l := range checkType[a.CheckMode] {
						val := atomic.LoadInt64(c.TopicStatistics[l.TopicName])
						fmt.Printf("topic [%v] 在执行任务数 [%v] \n", l.TopicName, val)
					}
					fmt.Printf("============================================ \n")
				}
			}
		}
	}(a)
}

// checkUnsubscribeTopic 检查是否可以取消订阅topic
func (a *AutoCloseMqComponent) checkUnsubscribeTopic(value int64, topic Topic) bool {
	if value > 0 {
		//fmt.Println("topic no end ", topic)
		return true
	}
	//if value == 0 {
	if value == 0 && a.EndMark {
		//fmt.Printf("topic %v 检测执行任务完成,开始退出 \n", topic)
		consumer := global.GetIoc().GetBean("consumer").(mq.Consumer)
		consumer.Unsubscribe(string(topic))
		a.UnsubscribeTopic = append(a.UnsubscribeTopic, topic)
	}
	return false
}

// UnsubscribeTopicInclude 检查是否可以取消订阅topic
func (a *AutoCloseMqComponent) UnsubscribeTopicInclude(topic Topic) bool {
	for _, t := range a.UnsubscribeTopic {
		if t == topic {
			return true
		}
	}
	return false
}
